<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Clickhouse\Guanyuan\GyShopCityConsumptionOpeningsCHModel;
use App\Remote\Guanyuan\GuanyuanRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

class SysGyShopCityConsumptionOpeningsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:sys:gyShopCityConsumptionOpenings';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步 城市消费签约和新开门店数 -> clickhouse';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        try {
            $fields = [
                "date",
                "province",
                "city",
                "openingCity",
                "statementCity",
                "numberOfNewStoresOpened",
                "expend",
                "threadQuantity",
                "numberOfClients",
                "numberOfStores",
                "refund",
                "calendarDate",
                "statementDate",
                "openingDate",
                "region",
                "province_1",
                "cityClassification",
                "dateSpecific"
            ];

            $redisClient = getRedisClient();
            $last        = GyShopCityConsumptionOpeningsCHModel::query()->orderByDesc("id")->first();
            if ($last) {
                $redisClient->set($this->signature, $last->id);
                $executeDate = $last->date;
            } else {
                $redisClient->set($this->signature, 0);
                $executeDate = "2021-01-01";
            }

            $nowDate     = Carbon::now()->format("Y-m-d");
            $batchInsert = [];
            while ($executeDate <= $nowDate) {
                $this->getOutput()
                     ->info("$executeDate 正在执行...  [内存占用:  " . (memory_get_usage(true) / 1024 / 1024) . "MB ]");

                $shopBusiness = GuanyuanRemote::sourceData(
                    'm6df2b63e7dd847bf885e090',
                    'a5a775c897fd64985b4cda31',
                    [
                        [
                            'name'        => '日期',
                            'filterType'  => 'EQ',
                            'filterValue' => [$executeDate]
                        ]
                    ],
                    0
                );

                if (empty($shopBusiness["data"]) && $nowDate != $executeDate) {
                    //执行脚本日期 == 拉取观远数据日期 数据为空此时为异常状态
                    throw new \Exception("观远拉取数据异常 [ $executeDate ]");
                }

                $this->getOutput()->info("当天数据量 :  " . count($shopBusiness["data"] ?? []));

                collect($shopBusiness["data"])->each(function ($shopBusinessRow) use (
                    $fields,
                    &$batchInsert,
                    &$redisClient
                ) {
                    $insert = [
                        "id"        => $redisClient->incr($this->signature),
                        "createdAt" => time()
                    ];
                    collect($shopBusinessRow)->each(function ($value, $key) use ($fields, &$insert, &$batchInsert) {
                        if (isset($fields[$key])) {
                            $insert[$fields[$key]] = $value;
                        } else {
                            return false;
                        }
                    });

                    array_push($batchInsert, $insert);
                });

                $executeDate = date("Y-m-d", strtotime(" +1 day", strtotime($executeDate)));
                unset($shopBusiness);
            }

            if ($batchInsert) {
                GyShopCityConsumptionOpeningsCHModel::query()->where("date", $last->date)->delete();
                collect($batchInsert)->chunk(500)->each(function (Collection $collection) {
                    GyShopCityConsumptionOpeningsCHModel::query()->insert($collection->values()->toArray());
                });
            }

            logInfo("{$this->description} 成功", collect([]), true, false);
        } catch (\Exception $exception) {
            logException("{$this->description} 失败 : {$exception->getMessage()}", $exception, null, true, true);
        }
        return 0;
    }
}
